package leetcode.d_100_199;

public class P124 {
    public static void main(String[] args) {

    }

    int maxPathSum;
    public int maxPathSum(TreeNode root) {
        maxPathSum = Integer.MIN_VALUE;
        maxSum(root);
        return maxPathSum;
    }

    public int maxSum(TreeNode root) {
        if (root == null) {
            return 0;
        }

        // 递归计算左右子节点的最大贡献值
        // 只有在最大贡献值大于 0 时，才会选取对应子节点
        int left = Math.max(maxSum(root.left), 0);
        int right = Math.max(maxSum(root.right), 0);

        // 节点的最大路径和取决于该节点的值与该节点的左右子节点的最大贡献值
        int pathSum = root.val + left + right;

        // 更新答案
        maxPathSum = Math.max(maxPathSum, pathSum);

        // 返回节点的最大贡献值
        return root.val + Math.max(left, right);
    }
}
